<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script>
        // 注意第二个参数 可以改变this指向

        var arr = [1, 2, 3, 4]
        arr.forEach(function (item, index, arr) {
            console.log(item, index, arr, this)
        }, {})

        Array.prototype._forEach = function (fn) {
            // this指向arr
            var context = arguments[1] || window
            if (typeof fn === 'function') {
                for (var i = 0; i < this.length; i++) {
                    fn.apply(context, [arr[i], i, this])
                }
            } else {
                throw new Error('参数必须是函数')
            }
        }

        arr._forEach(function (item, index, arr) {
            console.log(item, index, arr, this)
        }, {})

    </script>
</body>

</html>